package com.tt1000.settlementplatform;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PersistableBundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tt1000.settlementplatform.app.MyApplication;
import com.tt1000.settlementplatform.base.BaseFragment;
import com.tt1000.settlementplatform.bean.BaseBean;
import com.tt1000.settlementplatform.bean.HeartBean;
import com.tt1000.settlementplatform.bean.TaskBean;
import com.tt1000.settlementplatform.bean.TotalNum;
import com.tt1000.settlementplatform.bean.member.CommodityRecord;
import com.tt1000.settlementplatform.bean.member.CommodityTypeRecord;
import com.tt1000.settlementplatform.bean.member.DaoSession;
import com.tt1000.settlementplatform.bean.member.MemberTypeRecord;
import com.tt1000.settlementplatform.bean.member.StoreConfig;
import com.tt1000.settlementplatform.bean.member.SyncResultInfo;
import com.tt1000.settlementplatform.bean.member.SyncTableRecord;
import com.tt1000.settlementplatform.bean.member.SyncTableRecordDao;
import com.tt1000.settlementplatform.bean.member.TfCardInfo;
import com.tt1000.settlementplatform.bean.member.TfDiscountRecord;
import com.tt1000.settlementplatform.bean.member.TfMealTimes;
import com.tt1000.settlementplatform.bean.member.TfMemberAccountRecord;
import com.tt1000.settlementplatform.bean.member.TfMemberInfo;
import com.tt1000.settlementplatform.bean.member.TfPrintTask;
import com.tt1000.settlementplatform.bean.member.TfStoreRecord;
import com.tt1000.settlementplatform.bean.member.TfUserInfo;
import com.tt1000.settlementplatform.bean.result_info.VerifyMachineResultInfo;
import com.tt1000.settlementplatform.feature.BuiltInPrinter;
import com.tt1000.settlementplatform.feature.network.LocalRetrofit;
import com.tt1000.settlementplatform.utils.MyConstant;
import com.tt1000.settlementplatform.utils.MyUtil;
import com.tt1000.settlementplatform.view.HomeFragment;
import com.tt1000.settlementplatform.view.LoginFragment;
import com.tt1000.settlementplatform.view.OperationFragment;
import com.tt1000.settlementplatform.view.SettingFragment;
import com.tt1000.settlementplatform.view.presentation.SecondaryDisplayService;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observer;
import rx.schedulers.Schedulers;

public class MainActivity extends FragmentActivity implements View.OnClickListener {

    private static final String TAG = "mainmenu";
    public static final int WIFI_ERROR = 1011;
    public static final int WIFI_NORMAL = 1012;
    public static final int CANCEL_PROGRESS_DIALOG = 0x3011;
    public static final int START_SCHEDULE_TASK = 0x3012;
    //机器绑定成功
    public static final int BIND_MACHINE_SUCD = 0x3013;
    public static final int SHOW_BIND_SUCC = 0x3014;

    private Context mContext;

    private FragmentManager fragmentManager;
    private final int containerId = R.id.fragment_container;
    //nfc
    public NfcAdapter mNfcAdapter;
    public IntentFilter[] mIntentFilter = null;
    public PendingIntent mPendingIntent = null;
    public String[][] mTechList = null;
    private AlertDialog dialog;
    private TextView txAppTitle;
    public TextView txFps;
    private TextView txUserId;
    private TextView txVersion;
    private TextView txMachineName;
    private TextClock txDate;
    public ImageView ivWifi;
    private ImageView ivReadCard;
    private ImageButton ivPower;

    private ProgressDialog progressDialog;
    private AlertDialog exitSysDialog, backHomeDialog, backLoginDialog;

    public OnScanResultCallback callback;
    public OnBarcodeScannerCallback barcodeCallback;

    public static List<BaseFragment> fragmentList;
    // 当前登陆账号的操作员信息
    public TfUserInfo pUserInfo;
    public StoreConfig pStoreConfig;
    // 同步数据的个数
    public int syncNum = 0;
    public int taskCount = 0;

    public boolean isDestory = false;

    public List<TaskBean> taskList;
    // 网络连接是否断开
    public boolean wifiState = false;

    public boolean machineExpire = false;

    public static SyncTableRecord syncTableRecord = null;

    public LoginFragment loginFragment;

    public DaoSession session;
    // 是否在同步
    public boolean isSync = false;
    //是否是 刚登录完正在初始化
    private boolean isInit = false;
    private int init_index = 0;
    private int num = 0;

    public BuiltInPrinter pPrinter;

    public static boolean is_can = true;

    private ScheduledThreadPoolExecutor mExecutor = new ScheduledThreadPoolExecutor(5);

    public static ThreadPoolExecutor gTHREAD_POOL = new ThreadPoolExecutor(2,
            5,
            1,
            TimeUnit.SECONDS,
            new LinkedBlockingDeque<Runnable>());

    public static MainHandler gUiHandler;
    private String bindSuccMsg = "";
//    public NetworkConnectChangedReceiver networkReceiver;

    public class MainHandler extends Handler {
        @SuppressLint("ResourceAsColor")
        @Override
        public void handleMessage(final Message msg) {
            switch (msg.what) {
                case START_SCHEDULE_TASKS:
                    mExecutor.scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                            try {
                                if (MyUtil.obtainNetworkStatus(mContext)) {
                                    sendFps();
                                } else {
                                    gUiHandler.sendEmptyMessage(WIFI_ERROR);
                                }
                            } catch (Exception e) {
                                Log.d("frost", "fps error");
                            }
                        }
                    }, 0, 1, TimeUnit.SECONDS);
                    break;
                case BIND_MACHINE_SUCD:
                    bindSuccMsg = (String) msg.obj;
//                    break;
//                case MyConstant.SYNC_TABLE_DATA:
                    String machineNo = MyConstant.gSharedPre.getString(MyConstant.SP_MACHINE_NO, "");
                    boolean registerMachine = MyConstant.gSharedPre.getBoolean(MyConstant.SP_REGISTER_MACHINE, false);
                    if (registerMachine && !machineNo.isEmpty() && !progressDialog.isShowing()) {
                        progressDialog.show();
                    }
                    isInit = true;
                    initData();
                    break;
                case SHOW_BIND_SUCC:
                    showBindMachineSucc();
                    break;
                case MyConstant.CHANGE_APP_TITLE:
                    txAppTitle.setText(msg.obj.toString());
                    break;
                case 2:
                    long fps = (long) msg.obj;
                    if (fps <= 60) {
                        txFps.setTextColor(Color.parseColor("#33b422"));
                    } else if (fps <= 200) {
                        txFps.setTextColor(Color.parseColor("#fdcc23"));
                    } else {
                        txFps.setTextColor(Color.parseColor("#d5434a"));
                    }
                    txFps.setText(msg.obj + "ms");
                    break;
                case 6:
                    boolean isConnect = MyUtil.networkState;
                    if (isConnect) {
                        ivWifi.setImageResource(R.drawable.wifi_normal);
                        wifiState = true;
                        inlineUpdate();
                    } else {
                        ivWifi.setImageResource(R.drawable.wifi_error);
                        txFps.setText("网络断开");
                        wifiState = false;
                    }
                    break;
                case WIFI_ERROR:
                    ivWifi.setImageResource(R.drawable.wifi_error);
                    txFps.setText("网络断开");
                    wifiState = false;

                    break;
                case WIFI_NORMAL:
                    ivWifi.setImageResource(R.drawable.wifi_normal);
                    wifiState = true;
                    inlineUpdate();
                    break;
                case 7:
                    if (hasNfc(mContext)) {
                        ivReadCard.setImageResource(R.drawable.card_normal);
                    } else {
                        ivReadCard.setImageResource(R.drawable.card_error);
                    }
                    break;
                case MyConstant.REPLACE_FRAGMENT_TO_STACK:
                    BaseFragment stackFragment = (BaseFragment) msg.obj;
                    repleaseFragmentToStack(stackFragment);
                    break;
                case MyConstant.REPLACE_FRAGMENT_NORMAL:
                    BaseFragment normalFramgnet = (BaseFragment) msg.obj;
                    repleaseFragment(normalFramgnet);
                    break;
                case MyConstant.SHOW_PROGRESS_DIALOG:

                    break;
                case CANCEL_PROGRESS_DIALOG:
                    cancelProgressDiaglog();
                    break;
                case START_SCHEDULE_TASK://开启定时任务
                    //关于心跳的定时任务
                    Log.e("url", "-----------------START_SCHEDULE_TASK");
                    sendHeartbeatAtFixedRate();
//                    regularlyUpdateTable();
                    break;
                default:
                    break;
            }

        }
    }

    /**
     * 显示 绑定 成功的提示
     */
    private void showBindMachineSucc() {
        Log.i(TAG, "showBindMachineSucc: ");
        AlertDialog bindSuccDialog = new AlertDialog.Builder(mContext)
                .setTitle("提示")
                .setMessage(bindSuccMsg)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //跳转到登录界面
                        gUiHandler.obtainMessage(MyConstant.REPLACE_FRAGMENT_NORMAL, new LoginFragment()).sendToTarget();
                        dialog.cancel();
                    }
                })
                .create();
        bindSuccDialog.show();
    }

    //    public class NetworkConnectChangedReceiver extends BroadcastReceiver {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            // 判断连接的wifi是否是一个可用网络
//            if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
//                Parcelable parcelable = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
//                if (parcelable != null) {
//                    NetworkInfo networkInfo = (NetworkInfo) parcelable;
//                    // 当前连接成功或失败的状态
//                    NetworkInfo.State state = networkInfo.getState();
//                    // 判断网络是否已连接
//                    boolean isConnected = state == NetworkInfo.State.CONNECTED;
//                    if (isConnected) {
//                        ivWifi.setImageResource(R.drawable.wifi_normal);
//                        wifiState = true;
//                        inlineUpdate();
//                    } else {
//                        ivWifi.setImageResource(R.drawable.wifi_error);
//                        txFps.setText("网络断开");
//                        wifiState = false;
//                    }
//                }
//            }
//            // 监听网络连接,包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听
//            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
//                NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
//                if (info != null) {
//                    // 当前网络可用
//                    if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
//                        // 连上
//                        if (info.getType() == ConnectivityManager.TYPE_WIFI || info.getType() == ConnectivityManager.TYPE_MOBILE) {
//                            ivWifi.setImageResource(R.drawable.wifi_normal);
//                            wifiState = true;
//                            inlineUpdate();
//                        }
//                    } else {
//                        // 断开
//                        ivWifi.setImageResource(R.drawable.wifi_error);
//                        txFps.setText("网络断开");
//                        wifiState = false;
//                    }
//                }
//            }
//        }
//    }
    // 静态类，只需加载该类后就能实例化对象，否则非静态对象无法实例化
    public static class AutoStartRecevier extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
                Intent i = new Intent(context, MainActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    public static final int START_SCHEDULE_TASKS = 0x3111;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.GONE);
        }
        String crm_addr = MyConstant.gSharedPre.getString(MyConstant.SP_CRM_ADDRESS, "");
        if (TextUtils.isEmpty(crm_addr)) {
            MyConstant.gEditor.putString(MyConstant.SP_CRM_ADDRESS, "").commit();
        }

        mContext = this;
        session = MyApplication.getInstance();
        pPrinter = new BuiltInPrinter(this);
        gUiHandler = new MainHandler();
        taskList = new ArrayList<>();
        initView();
        initNFC();
        //initData();
        initFragment();

        Intent intent = new Intent(MainActivity.this, SecondaryDisplayService.class);
        startService(intent);
        bindService(intent, mConn, Service.BIND_AUTO_CREATE);

//        if (MyUtil.obtainNetworkStatus(mContext)) {
        verifyMachineDate();
        MainActivity.gUiHandler.sendEmptyMessage(MainActivity.START_SCHEDULE_TASKS);
//        }
        //sendHeartbeatAtFixedRate();
        //regularlyUpdateTable();

    }

    /**
     * 在固定时间点 发送心跳服务
     */
    private void sendHeartbeatAtFixedRate() {
        try {
            // 网络延迟: ms
            mExecutor.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG, "run: " + MyUtil.networkState);
                    Log.d("url", "run: " + MyUtil.networkState);
                    String ip = MyConstant.gSharedPre.getString(MyConstant.SP_Server_IP,"");
                    String port = MyConstant.gSharedPre.getString(MyConstant.SP_Server_PORT,"");
                    String url = "http://" + ip + ":" + port + "/k-occ/sync/heart";
                    if (MyUtil.obtainNetworkStatus(mContext)) {
                        final long startTime = System.currentTimeMillis();
                        Log.e(TAG, "心跳-heartbeat");
                        RequestBody requestBody = new FormBody.Builder().build();
                        OkHttpClient client = new OkHttpClient.Builder()
                                .build();
                        Request request = new Request.Builder()
                                .url(url)
                                .post(requestBody)
                                .build();
                        client.newCall(request).enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                gUiHandler.obtainMessage(WIFI_ERROR).sendToTarget();
                                gUiHandler.sendEmptyMessage(CANCEL_PROGRESS_DIALOG);
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                gUiHandler.obtainMessage(WIFI_NORMAL).sendToTarget();
                                String body = response.body().string();
                                Gson gson = new Gson();
                                try {
                                    HeartBean bean = gson.fromJson(body, HeartBean.class);
                                    if (bean.getCode().equals("00000") && bean.isResult()) {
                                        String systemTime = bean.getData().get(0).getTime();
                                        long responseTime = 0;
                                        try {
                                            responseTime = MyUtil.stringToLong(systemTime, "yyyy-MM-dd HH:mm:ss");
                                            long sysTime = System.currentTimeMillis();
                                            if (responseTime - sysTime < 1000 * 3600 * 24) {
                                            } else {
                                                showMessage("错误", "设备时间错误" + "\n" + "请矫正后重新登录");
                                            }
                                        } catch (ParseException e) {
                                        }
                                    }
                                } catch (Exception e) {
                                    gUiHandler.sendEmptyMessage(WIFI_ERROR);
                                    Log.e("frost", e.getMessage());
                                }
                            }
                        });
                    }
                }
            }, 0, MyConstant.HEARTBEAT_INTERVAL_TIME_, TimeUnit.SECONDS);


            //sendHeratDB();


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void cancelProgressDiaglog() {
        if (progressDialog.isShowing()) {
            progressDialog.cancel();
        }
    }
    public void showMessage(final String title, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.setTitle(title);
                dialog.setMessage(msg);
                dialog.show();
            }
        });
    }
    private void sendFps() {
        try {
            String serverIp = MyConstant.gSharedPre.getString(MyConstant.SP_Server_IP, "");
            String delay = new String();
            Process p = null;
//            String serverIp = ip.substring(8);

            p = Runtime.getRuntime().exec("ping -c 1 -w 20 " + serverIp);
//            p = Runtime.getRuntime().exec("/system/bin/ping -t " + serverIp);
            int status = p.waitFor();
            if (status == 0) {
                BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String str = new String();
                while ((str = buf.readLine()) != null) {
                    if (str.contains("avg")) {
//                        Log.e("frost_ping", str);
                        int i = str.indexOf("/", 20);
                        int j = str.indexOf(".", i);
                        delay = str.substring(i + 1, j);
                    }
                }
                gUiHandler.obtainMessage(2, Long.parseLong(delay)).sendToTarget();
            }
        } catch (IOException e) {
            Log.e("frost_ping:", e.getMessage());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void verifyMachineDate() {
        try {
            // 验证机器到期时间
            String machineNo = MyConstant.gSharedPre.getString(MyConstant.SP_MACHINE_NO, "");
            long machineExpire = MyConstant.gSharedPre.getLong(MyConstant.SP_MACHINE_EXPIRE, 0);
            // Log.e("url","machineExpire:" + machineExpire);
//            Log.e("url","MyUtil.dateConversion(machineExpire):" + MyUtil.dateConversion(machineExpire));
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
//            Log.e("url","format:" + format.format(new Date(machineExpire)));
            String time = format.format(new Date(machineExpire));
            // Log.e("url","time:" + time);
            SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            date = format2.parse(time);
            //  Log.e("url","format.parse:" + date);
            machineExpire = date.getTime();
            // Log.e("url","date:" + date.getTime());
            //if (machineExpire != 0 && machineExpire < System.currentTimeMillis()) {
            long daytimes = 15 * 24 * 60 * 60 * 1000;
            if (machineExpire != 0 && machineExpire - daytimes < System.currentTimeMillis()) {
                MyConstant.gEditor.putBoolean(MyConstant.SP_REGISTER_MACHINE, false);
                MyConstant.gEditor.commit();
                long finalMachineExpire = machineExpire;
                gUiHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (loginFragment != null) {
                                // 激活界面显示
                                loginFragment.constraintLayout.setVisibility(View.VISIBLE);                  ///crash--------
                                loginFragment.txExpireDate.setText(time);    ///crash--------

                                if (finalMachineExpire < System.currentTimeMillis()) {
                                    loginFragment.btnLogin.setEnabled(false);
                                } else {
                                    loginFragment.btnLogin.setEnabled(true);
                                }
                            }
                        } catch (Exception e) {
                            Log.e("CrashHandler", "loginFragment.." + e.getMessage());
                        }
                    }
                }, 1200);
            }
            if (machineNo != null && machineNo.length() > 0) {
                try {

                    LocalRetrofit.createService().verifyMachineDate(machineNo)
                            .subscribeOn(Schedulers.io())
                            .subscribe(new Observer<BaseBean<VerifyMachineResultInfo>>() {
                                @Override
                                public void onCompleted() {

                                }

                                @Override
                                public void onError(Throwable e) {

                                }

                                @Override
                                public void onNext(BaseBean<VerifyMachineResultInfo> verifyMachineResultInfoBaseBean) {

                                    final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    long curTime = System.currentTimeMillis();
                                    // 0 正常 1 停止
                                    for (final VerifyMachineResultInfo verifyMachineResultInfo : verifyMachineResultInfoBaseBean.getData()) {
                                        if (verifyMachineResultInfo != null) {
                                            if (verifyMachineResultInfo.getVAILD_TIME() > 0) {
                                                MyConstant.gEditor.putLong(MyConstant.SP_MACHINE_EXPIRE, verifyMachineResultInfo.getVAILD_TIME());
                                                MyConstant.gEditor.commit();
                                            }
                                            if (verifyMachineResultInfo.getUSE_STATUS().equals("1") || curTime > verifyMachineResultInfo.getVAILD_TIME()) {
                                                MyConstant.gEditor.putBoolean(MyConstant.SP_REGISTER_MACHINE, false);
                                                MyConstant.gEditor.commit();
                                            }
                                        }
                                    }
                                }
                            });

                    /*
                    String ip = gSharedPre.getString(MyConstant.SP_Server_IP, "");
                    String port = gSharedPre.getString(MyConstant.SP_Server_PORT, "");
                    String url = "http://" + ip + ":" + port + "/k-occ/machineManager/details/"+machineNo;
                    OkHttpClient client = new OkHttpClient.Builder().build();

                    final Request request = new Request.Builder()
                            .url(url)
                            .build();

                    Log.e("pay","getMemberCardBalance....2.1");
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.d(TAG, "onFailure: " + e.getMessage());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            try {
                                String body = response.body().string();
                                Log.e("look","verifyMachineResultInfo body:"+body);

                            } catch (Exception e) {

                            }
                        }
                    });
                    */
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Log.e("verifyMachineDate", "machineNo2:" + machineNo);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean mShowing = false;
    private SecondaryDisplayService mService = null;
    private ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = ((SecondaryDisplayService.MsgBinder) service).getService();
            //refresh UI
            if (mService.isPlaying()) {
                Log.d(TAG, "video playing");
                mShowing = true;
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            if (mService != null) {
                mService = null;
            }
        }
    };

    public void showPay(String type, String price) {
        mShowing = true;
        if (mService != null) {
            mService.play(SecondaryDisplayService.TYPE_SHOW, type, price);
        }
    }

    public void showPay(Activity activity, String type, String price, String phone, String name, String blance) {
        mShowing = true;
        if (mService != null) {
            mService.play(activity, SecondaryDisplayService.TYPE_SHOW, type, price, phone, name, blance);
        }
    }

//    private void initReceiver() {
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
//        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
//        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//        if (networkReceiver == null) {
//            networkReceiver = new NetworkConnectChangedReceiver();
//        }
//        registerReceiver(networkReceiver, filter);
//    }

    private void initView() {

        txAppTitle = findViewById(R.id.app_title);
        txFps = findViewById(R.id.tx_fps);
        txUserId = findViewById(R.id.tx_user_id);
        txVersion = findViewById(R.id.tx_version_info);
        txMachineName = findViewById(R.id.tx_login_user_name);
        ivWifi = findViewById(R.id.iv_wifi);
        ivReadCard = findViewById(R.id.iv_read_card);
        ivPower = findViewById(R.id.iv_power);
        progressDialog = new ProgressDialog(mContext);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setMessage("同步中...");
        dialog = new AlertDialog.Builder(mContext)
                .setCancelable(false)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        exit();
                    }
                })
                .create();
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext)
                .setNegativeButton("取消", null);
        exitSysDialog = dialogBuilder.setMessage("是否退出系统？")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        android.os.Process.killProcess(android.os.Process.myPid());
                        finish();
                    }
                })
                .create();

        backLoginDialog = dialogBuilder.setMessage("是否返回登录界面？")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        repleaseFragment(new LoginFragment());
                        txAppTitle.setText("登录");
                    }
                })
                .create();

        backHomeDialog = dialogBuilder.setMessage("是否返回主界面？")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        repleaseFragment(new HomeFragment());
                        txAppTitle.setText("主界面");
                    }
                })
                .create();

//        notifyDialog = dialogBuilder.setMessage("当前机器不可用")
//                .setTitle("提示")
//                .setPositiveButton("确认", null)
//                .create();

        ivPower.setOnClickListener(this);

        // 判断nfc是否开启
        gUiHandler.obtainMessage(7).sendToTarget();
        /*
         每隔一段时间去检测wifi状态和nfc状态-
         check the wifi status every once in a while
          */
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        Runnable task = new Runnable() {
            @Override
            public void run() {
                gUiHandler.obtainMessage(6).sendToTarget();
                gUiHandler.obtainMessage(7).sendToTarget();
            }
        };
        scheduledExecutorService.scheduleAtFixedRate(task, 0, 60, TimeUnit.SECONDS);
        // 机器号显示
        String machineName = MyConstant.gSharedPre.getString(MyConstant.SP_MACHINE_NAME, "");
        txMachineName.setText(machineName);
    }

    private void initNFC() {
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            Toast.makeText(this, "不支持NFC功能", Toast.LENGTH_SHORT).show();
        } else if (!mNfcAdapter.isEnabled()) {
            Intent intent = new Intent(Settings.ACTION_NFC_SETTINGS);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        }
        Intent subIntent = new Intent();
        subIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        mPendingIntent = PendingIntent.getActivity(this, 0, subIntent, 0);
        IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);

        try {
            // 接受所有类型
            filter.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            e.printStackTrace();
        }
        mIntentFilter = new IntentFilter[]{filter, filter2};
        mTechList = null;
    }

    private void initData() {
        Log.i(TAG, "initData: ");
        syncNum = 0;
        syncData();

        if (MyUtil.obtainNetworkStatus(mContext)) {
            if (MyUtil.isConfigServer()) {
                if (!txFps.equals("网络断开")) {
                    //syncNum = 0;
                    //syncData();
                }
            } else {
                if (isExistsUserInfo()) {
                    AlertDialog dialog = new AlertDialog.Builder(mContext)
                            .setTitle("警告")
                            .setMessage("当前服务器地址尚未配置或配置错误，无法更新数据")
                            .create();
                    dialog.show();
                }
            }
        } else {
            Toast.makeText(mContext, "当前无网络连接，无法更新数据", Toast.LENGTH_SHORT).show();
        }
    }

    private void initFragment() {
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if (!isExistsUserInfo()) {
            SettingFragment settingFragment = new SettingFragment();
            transaction.add(containerId, settingFragment);
            transaction.show(settingFragment);
        } else {
            loginFragment = new LoginFragment();
            transaction.add(containerId, loginFragment);
            transaction.show(loginFragment);
        }
        transaction.commit();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_power:
                if (pUserInfo != null) {
                    switch (pUserInfo.getUTYPE()) {
                        case "1":
                            //verifyMachineDate();
                            if (txAppTitle.getText().equals(getString(R.string.operate))) {
                                backLoginDialog.show();
                            }
                            break;
                        case "2":
                        case "3":
                            if (!txAppTitle.getText().equals("主界面")) {
                                backHomeDialog.show();
                            } else {
                                backLoginDialog.show();
                            }
                            break;
                    }
                } else {
                    exitSysDialog.show();
                }
                break;
            default:
                break;
        }
    }

    public boolean hasNfc(Context context) {
        boolean bRet = false;
        if (context == null) {
            return bRet;
        }
        NfcManager manager = (NfcManager) context.getSystemService(Context.NFC_SERVICE);
        NfcAdapter adapter = manager.getDefaultAdapter();
        if (adapter != null && adapter.isEnabled()) {
            // adapter存在，能启用
            bRet = true;
        }
        return bRet;
    }

    /**
     * 同步数据
     */

    boolean isFirstIn = false;

    public void syncData() {
        try {
            Log.i(TAG, "syncData: ");
            syncTable(1111, "", 0, 0);
            taskList.clear();
            getTaskType();
            Log.i(TAG, "syncData: 4");
            //if (taskList.isEmpty()) {
            //    syncTable(1111, "",0,0);
            //    return;
            //}
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("syncData", "syncData Exception");
            cancelProgressDiaglog();
        }
    }

    /**
     * copy operation
     */
    public void copy() {
        try {
            InputStream input = null;
            FileOutputStream output;
            try {

                File downloadFile = new File(Environment.getExternalStorageDirectory().getPath() + "/Download");
                if (!downloadFile.exists()) {
                    downloadFile.mkdirs();
                }
                File dbFile = new File(downloadFile.getPath() + "/outputDatabase.db");
                if (dbFile.exists()) {
                    dbFile.delete();
                }
                input = new FileInputStream(new File(MyConstant.DB_PATH + MyConstant.DB_NAME));
                output = new FileOutputStream(dbFile);

                byte[] buffer = new byte[8192];
                int count = 0;
                while ((count = input.read(buffer)) != -1) {
                    output.write(buffer, 0, count);
                }
                output.flush();
                output.close();
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void syncTable(final int type, final String tableName, long l_updatetime, int page_no) {
        Log.e("url", "syncData type:" + type);
//        if (!MyUtil.obtainNetworkStatus(mContext) &&!MyUtil.isConfigServer()) {
        Log.i(TAG, "networkstate->syncTable->" + MyUtil.obtainNetworkStatus(mContext));
        if (!MyUtil.obtainNetworkStatus(mContext)) {
            return;
        }
        final DaoSession session = MyApplication.getInstance();
        String updateTime = "";
        String t_record_name = "";

        if (!TextUtils.isEmpty(tableName)) {
            List<SyncTableRecord> syncTableRecordList = session.queryBuilder(SyncTableRecord.class)
                    .where(SyncTableRecordDao.Properties.TABLENAME.eq(tableName))
                    .build()
                    .list();
            if (syncTableRecordList != null && syncTableRecordList.size() > 0) {
                syncTableRecord = syncTableRecordList.get(0);
            }
        }

        try {
            updateTime = MyUtil.dateConversion(l_updatetime);
        } catch (NumberFormatException e) {

        }

        if (!is_can) {
            return;
        }

        Log.d("cxy", "table_type:" + type + " t_record_name:" + t_record_name + " l_updatetime" + l_updatetime + " updateTime:" + updateTime + " page_no->" + page_no);
        String clienCode = MyConstant.gSharedPre.getString(MyConstant.CLIENT_CODE, "");
        String storeCode = MyConstant.gSharedPre.getString(MyConstant.STORE_CODE, "");
        final Map<String, Object> map = new HashMap<String, Object>();
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("updatetime", updateTime);
        map.put("client_code", clienCode);
        map.put("store_code", storeCode);
        map.put("api", "1");
        map.put("pageNo", "" + page_no);
        Log.i("syncData", "timestamp->" + map.get("timestamp") + "  updatetime->" + map.get("updatetime")
                + "   client_code->" + map.get("client_code") + "  store_code->" + map.get("store_code")
                + "   api->" + map.get("api") + "  pageNo->" + map.get("pageNo"));
        Log.d(TAG, "syncTable: tablename :  " + tableName + " startTime " + MyUtil.obtainCurrentSysDate(2));

        switch (type) {
            case 0:
                LocalRetrofit.createService().syncCommodityRecordData(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<?>>() {
                            @Override
                            public void onCompleted() {
                                isSync = false;
                                syncNum += 1;
                                if (isInit) {
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
//                                Log.d(TAG, "onError: " + e.getMessage());
                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                task_table_index++;
                            }

                            @Override
                            public void onNext(final SyncResultInfo<?> objectSyncResultInfo) {
                                Log.i("syncData", "table->commodity_record->count->" + objectSyncResultInfo.getData().size());
                                if (objectSyncResultInfo.getData().isEmpty()) {
                                    verifyDataNum(type);
                                    task_page_no = 0;
                                    task_table_index++;
                                    return;
                                } else {
                                    task_page_no++;
                                }
                                session.runInTx(new Runnable() {
                                    @Override
                                    public void run() {
                                        long max_time = 0;
                                        for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {
                                            CommodityRecord record = (CommodityRecord) objectSyncResultInfo.getData().get(i);

                                            if (max_time < record.getUPDATETIME()) {
                                                max_time = record.getUPDATETIME();
                                            }
                                            session.insertOrReplace(record);

                                        }

                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(max_time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                    }
                                });
                                //Log.d("look","table_type:"+type+" tname:"+syncTableRecord.getTABLENAME()+" objectSyncResultInfo.getData().size():"+objectSyncResultInfo.getData().size()+" max_time"+MyUtil.dateConversion(max_time));
                            }
                        });
                break;
            case 1:
                LocalRetrofit.createService().syncCommodityTypeRecordData(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<CommodityTypeRecord>>() {
                            @Override
                            public void onCompleted() {
                                isSync = false;
                                syncNum += 1;
                                if (isInit) {
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                task_table_index++;
                            }

                            @Override
                            public void onNext(final SyncResultInfo<CommodityTypeRecord> objectSyncResultInfo) {
                                Log.i("syncData", "table->commodity_type_record->count->" + objectSyncResultInfo.getData().size());
                                if (objectSyncResultInfo.getData().isEmpty()) {
                                    verifyDataNum(type);
                                    task_page_no = 0;
                                    task_table_index++;
                                    return;
                                } else {
                                    task_page_no++;
                                }
                                session.runInTx(new Runnable() {
                                    @Override
                                    public void run() {
                                        long max_time = 0;
                                        for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {
                                            CommodityTypeRecord commodityTypeRecord = (CommodityTypeRecord) objectSyncResultInfo.getData().get(i);

                                            if (max_time < commodityTypeRecord.getUPDATETIME()) {
                                                max_time = commodityTypeRecord.getUPDATETIME();
                                            }
                                            session.insertOrReplace(commodityTypeRecord);
                                        }

                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(max_time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                    }
                                });
                                //Log.d("look","table_type:"+type+" tname:"+syncTableRecord.getTABLENAME()+" objectSyncResultInfo.getData().size():"+objectSyncResultInfo.getData().size()+" max_time"+MyUtil.dateConversion(max_time));
                            }
                        });
                break;
            case 2:
                LocalRetrofit.createService().syncMemberTypeRecordData(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<MemberTypeRecord>>() {
                            @Override
                            public void onCompleted() {
                                isSync = false;
                                syncNum += 1;
                                if (isInit) {
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                task_table_index++;
                            }

                            @Override
                            public void onNext(final SyncResultInfo<MemberTypeRecord> objectSyncResultInfo) {
                                Log.i("syncData", "table->member_type_record->count->" + objectSyncResultInfo.getData().size());
                                if (objectSyncResultInfo.getData().isEmpty()) {
                                    verifyDataNum(type);
                                    task_page_no = 0;
                                    task_table_index++;
                                    return;
                                } else {
                                    task_page_no++;
                                }
                                session.runInTx(new Runnable() {
                                    @Override
                                    public void run() {
                                        long max_time = 0;
                                        for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {
                                            MemberTypeRecord memberTypeRecord = (MemberTypeRecord) objectSyncResultInfo.getData().get(i);

                                            if (max_time < memberTypeRecord.getUPDATETIME()) {
                                                max_time = memberTypeRecord.getUPDATETIME();
                                            }

                                            session.insertOrReplace(memberTypeRecord);
                                        }

                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(max_time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                    }
                                });
                                //Log.d("look","table_type:"+type+" tname:"+syncTableRecord.getTABLENAME()+" objectSyncResultInfo.getData().size():"+objectSyncResultInfo.getData().size()+" max_time"+MyUtil.dateConversion(max_time));
                            }
                        });
                break;
            case 3:
                LocalRetrofit.createService().syncStoreConfigData(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<StoreConfig>>() {
                            @Override
                            public void onCompleted() {
                                isSync = false;
                                syncNum += 1;
                                if (isInit) {
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                task_table_index++;
                            }

                            @Override
                            public void onNext(final SyncResultInfo<StoreConfig> objectSyncResultInfo) {
                                Log.i("syncData", "table->store_config->count->" + objectSyncResultInfo.getData().size());
                                if (objectSyncResultInfo.getData().isEmpty()) {
                                    verifyDataNum(type);
                                    task_page_no = 0;
                                    task_table_index++;
                                    return;
                                } else {
                                    task_page_no++;
                                }
                                session.runInTx(new Runnable() {
                                    @Override
                                    public void run() {
                                        long max_time = 0;
                                        for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {
                                            StoreConfig storeConfig = (StoreConfig) objectSyncResultInfo.getData().get(i);

                                            if (max_time < storeConfig.getUPDATETIME()) {
                                                max_time = storeConfig.getUPDATETIME();
                                            }

                                            if (storeConfig.getSEQNO() == null) {
                                                continue;
                                            }
                                            session.insertOrReplace(storeConfig);
                                        }

                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(max_time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                    }
                                });
                                //Log.d("look","table_type:"+type+" tname:"+syncTableRecord.getTABLENAME()+" objectSyncResultInfo.getData().size():"+objectSyncResultInfo.getData().size()+" max_time"+MyUtil.dateConversion(max_time));
                            }
                        });
                break;
            case 4:
                LocalRetrofit.createService().syncTfCardInfoData(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<TfCardInfo>>() {
                            @Override
                            public void onCompleted() {
                                isSync = false;
                                syncNum += 1;
//                                Log.d(TAG, "syncTable: tablename :  " + tableName +" insert done Time :  " + MyUtil.obtainCurrentSysDate(2));
                                if (isInit) {
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                task_table_index++;
                            }

                            @Override
                            public void onNext(final SyncResultInfo<TfCardInfo> objectSyncResultInfo) {
                                Log.d(TAG, "syncTable: tablename :  " + tableName + " download Time " + MyUtil.obtainCurrentSysDate(2));
                                Log.i("syncData", "table->tf_cardinfo->count->" + objectSyncResultInfo.getData().size());
                                if (objectSyncResultInfo.getData().isEmpty()) {
                                    verifyDataNum(type);
                                    task_page_no = 0;
                                    task_table_index++;
                                    return;
                                } else {
                                    task_page_no++;
                                }
                                session.runInTx(new Runnable() {
                                    @Override
                                    public void run() {
                                        long max_time = 0;
//                                long time = 0;
                                        for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {

                                            TfCardInfo tfCardInfo = (TfCardInfo) objectSyncResultInfo.getData().get(i);
//                                    time = tfCardInfo.getUPDATETIME();
                                            //Log.d("look","table_type:"+type+" time:"+MyUtil.dateConversion(time));
                                            if (max_time < tfCardInfo.getUPDATETIME()) {
                                                max_time = tfCardInfo.getUPDATETIME();
                                            }
                                            session.insertOrReplace(tfCardInfo);
                                        }
                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(max_time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                    }
                                });
                                //Log.d(TAG, "syncTable: tablename :  " + tableName +" insert done Time :  " + MyUtil.obtainCurrentSysDate(2));

                                //Log.d("look","table_type:"+type+" tname:"+syncTableRecord.getTABLENAME()+" objectSyncResultInfo.getData().size():"+objectSyncResultInfo.getData().size()+" time:"+MyUtil.dateConversion(time)+" max_time"+MyUtil.dateConversion(max_time));
                            }
                        });
                break;
            case 5:
                LocalRetrofit.createService().syncTfDiscountRecordData(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<TfDiscountRecord>>() {
                            @Override
                            public void onCompleted() {
                                isSync = false;
                                syncNum += 1;
                                if (isInit) {
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                task_table_index++;
                            }

                            @Override
                            public void onNext(final SyncResultInfo<TfDiscountRecord> objectSyncResultInfo) {
                                Log.i("syncData", "table->tf_discount_record->count->" + objectSyncResultInfo.getData().size());
                                if (objectSyncResultInfo.getData().isEmpty()) {
                                    verifyDataNum(type);
                                    task_page_no = 0;
                                    task_table_index++;
                                    return;
                                } else {
                                    task_page_no++;
                                }
                                session.runInTx(new Runnable() {
                                    @Override
                                    public void run() {
                                        long max_time = 0;
                                        for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {
                                            TfDiscountRecord discountRecord = (TfDiscountRecord) objectSyncResultInfo.getData().get(i);

                                            if (max_time < discountRecord.getUPDATETIME()) {
                                                max_time = discountRecord.getUPDATETIME();
                                            }
                                            session.insertOrReplace(discountRecord);
                                        }

                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(max_time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                    }
                                });
                                //Log.d("look","table_type:"+type+" tname:"+syncTableRecord.getTABLENAME()+" objectSyncResultInfo.getData().size():"+objectSyncResultInfo.getData().size()+" max_time"+MyUtil.dateConversion(max_time));
                            }
                        });
                break;
            case 6:
                LocalRetrofit.createService().syncTfMealTimesData(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<TfMealTimes>>() {
                            @Override
                            public void onCompleted() {
//                                Log.d(TAG, "onCompleted: ");
                                isSync = false;
                                syncNum += 1;
                                if (isInit) {
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {

//                                Log.d(TAG, "onError: " + e.getMessage());
                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                task_table_index++;
                            }

                            @Override
                            public void onNext(final SyncResultInfo<TfMealTimes> objectSyncResultInfo) {
                                Log.e("url", "syncTfMealTimesData");
                                Log.i("syncData", "table->tf_mealtimes->count->" + objectSyncResultInfo.getData().size());
                                if (objectSyncResultInfo.getData().isEmpty()) {
                                    verifyDataNum(type);
                                    task_page_no = 0;
                                    task_table_index++;
                                    return;
                                } else {
                                    task_page_no++;
                                }
                                session.runInTx(new Runnable() {
                                    @Override
                                    public void run() {
                                        long max_time = 0;
                                        for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {
                                            TfMealTimes mealTimes = (TfMealTimes) objectSyncResultInfo.getData().get(i);

                                            if (max_time < mealTimes.getUPDATETIME()) {
                                                max_time = mealTimes.getUPDATETIME();
                                            }
                                            session.insertOrReplace(mealTimes);
                                        }

                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(max_time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                    }
                                });
                                //Log.d("look","table_type:"+type+" tname:"+syncTableRecord.getTABLENAME()+" objectSyncResultInfo.getData().size():"+objectSyncResultInfo.getData().size()+" max_time"+MyUtil.dateConversion(max_time));
                            }
                        });
                break;
            case 7:
                LocalRetrofit.createService().syncTfMemberAccountRecordData(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<TfMemberAccountRecord>>() {
                            @Override
                            public void onCompleted() {
                                Log.i("look", "table->tTfMemberAccountRecord onCompleted");
                                isSync = false;
                                syncNum += 1;
                                if (isInit) {
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.i("look", "table->tTfMemberAccountRecord onError");
//                                Log.d(TAG, "onError: " + e.getMessage());

                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                task_table_index++;
                            }

                            @Override
                            public void onNext(final SyncResultInfo<TfMemberAccountRecord> objectSyncResultInfo) {
                                Log.i("look", "table->tTfMemberAccountRecord onNext");

                                Log.i("syncData", "table->tf_member_account_record->count->" + objectSyncResultInfo.getData().size());
                                if (objectSyncResultInfo.getData().isEmpty()) {
                                    Log.i("look", "table->tTfMemberAccountRecord :isEmpty1");
                                    verifyDataNum(type);
                                    task_page_no = 0;
                                    task_table_index++;
                                    return;
                                } else {
                                    Log.i("look", "table->tTfMemberAccountRecord :isEmpty2");
                                    task_page_no++;
                                }
                                session.runInTx(new Runnable() {
                                    @Override
                                    public void run() {
                                        long max_time = 0;
                                        for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {
                                            TfMemberAccountRecord memberAccountRecord = (TfMemberAccountRecord) objectSyncResultInfo.getData().get(i);

                                            if (max_time < memberAccountRecord.getUPDATETIME()) {
                                                max_time = memberAccountRecord.getUPDATETIME();
                                            }
                                            session.insertOrReplace(memberAccountRecord);
                                        }

                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(max_time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                    }
                                });
                                //Log.d("look","table_type:"+type+" tname:"+syncTableRecord.getTABLENAME()+" objectSyncResultInfo.getData().size():"+objectSyncResultInfo.getData().size()+" max_time"+MyUtil.dateConversion(max_time));
                            }
                        });
                break;
            case 8:
                LocalRetrofit.createService().syncTfMemberInfoData(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<TfMemberInfo>>() {
                            @Override
                            public void onCompleted() {
                                isSync = false;
                                syncNum += 1;
                                if (isInit) {
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
//                                Log.d(TAG, "onError: " + e.getMessage());
                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                task_table_index++;
                            }

                            @Override
                            public void onNext(final SyncResultInfo<TfMemberInfo> objectSyncResultInfo) {
                                Log.i("syncData", "table->tf_memberinfo->count->" + objectSyncResultInfo.getData().size());
                                if (objectSyncResultInfo.getData().isEmpty()) {
                                    verifyDataNum(type);
                                    task_page_no = 0;
                                    task_table_index++;
                                    return;
                                } else {
                                    task_page_no++;
                                }
                                session.runInTx(new Runnable() {
                                    @Override
                                    public void run() {
                                        long max_time = 0;
                                        for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {
                                            TfMemberInfo memberInfo = (TfMemberInfo) objectSyncResultInfo.getData().get(i);

                                            if (max_time < memberInfo.getUPDATETIME()) {
                                                max_time = memberInfo.getUPDATETIME();
                                            }
                                            session.insertOrReplace(memberInfo);
                                        }

                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(max_time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                    }
                                });
                                //Log.d("look","table_type:"+type+" tname:"+syncTableRecord.getTABLENAME()+" objectSyncResultInfo.getData().size():"+objectSyncResultInfo.getData().size()+" max_time"+MyUtil.dateConversion(max_time));
                            }
                        });
                break;
            case 9:
                LocalRetrofit.createService().syncTfPrintTaskData(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<TfPrintTask>>() {
                            @Override
                            public void onCompleted() {
                                isSync = false;
                                syncNum += 1;
                                if (isInit) {
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                task_table_index++;
                            }

                            @Override
                            public void onNext(final SyncResultInfo<TfPrintTask> objectSyncResultInfo) {
                                Log.i("syncData", "table->tf_print_task->count->" + objectSyncResultInfo.getData().size());
                                if (objectSyncResultInfo.getData().isEmpty()) {
                                    verifyDataNum(type);
                                    task_page_no = 0;
                                    task_table_index++;
                                    return;
                                } else {
                                    task_page_no++;
                                }
                                session.runInTx(new Runnable() {
                                    @Override
                                    public void run() {
                                        long max_time = 0;
                                        for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {
                                            TfPrintTask printTask = (TfPrintTask) objectSyncResultInfo.getData().get(i);

                                            if (max_time < printTask.getUPDATETIME()) {
                                                max_time = printTask.getUPDATETIME();
                                            }
                                            session.insertOrReplace(printTask);
                                        }

                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(max_time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                    }
                                });
                                //Log.d("look","table_type:"+type+" tname:"+syncTableRecord.getTABLENAME()+" objectSyncResultInfo.getData().size():"+objectSyncResultInfo.getData().size()+" max_time"+MyUtil.dateConversion(max_time));
                            }
                        });
                break;
            case 10:
                LocalRetrofit.createService().syncTfUserInfoData(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<TfUserInfo>>() {
                            @Override
                            public void onCompleted() {
                                isSync = false;
                                syncNum += 1;
                                if (isInit) {
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                task_table_index++;
                            }

                            @Override
                            public void onNext(final SyncResultInfo<TfUserInfo> objectSyncResultInfo) {
                                Log.i("syncData", "table->tf_userinfo->count->" + objectSyncResultInfo.getData().size());
                                if (objectSyncResultInfo.getData().isEmpty()) {
                                    verifyDataNum(type);

                                    task_page_no = 0;
                                    task_table_index++;
                                    return;
                                } else {
                                    task_page_no++;
                                }
                                session.runInTx(new Runnable() {
                                    @Override
                                    public void run() {
                                        long max_time = 0;
                                        for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {
                                            TfUserInfo userInfo = (TfUserInfo) objectSyncResultInfo.getData().get(i);

                                            if (max_time < userInfo.getUPDATETIME()) {
                                                max_time = userInfo.getUPDATETIME();
                                            }
                                            session.insertOrReplace(userInfo);
                                        }

                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(max_time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                    }
                                });
                                //Log.d("look","table_type:"+type+" tname:"+syncTableRecord.getTABLENAME()+"  objectSyncResultInfo.getData().size():"+objectSyncResultInfo.getData().size()+" max_time"+MyUtil.dateConversion(max_time));
                            }
                        });
                break;
            case 11:
                LocalRetrofit.createService().syncTfStoreRecordData(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<TfStoreRecord>>() {
                            @Override
                            public void onCompleted() {
                                isSync = false;
                                syncNum += 1;
                                if (isInit) {
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                task_table_index++;
                            }

                            @Override
                            public void onNext(final SyncResultInfo<TfStoreRecord> objectSyncResultInfo) {
                                Log.i("syncData", "table->tf_store_record->count->" + objectSyncResultInfo.getData().size());
                                if (objectSyncResultInfo.getData().isEmpty()) {
                                    verifyDataNum(type);

                                    task_page_no = 0;
                                    task_table_index++;
                                    return;
                                } else {
                                    task_page_no++;
                                }
                                session.runInTx(new Runnable() {
                                    @Override
                                    public void run() {
                                        long max_time = 0;
                                        for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {
                                            TfStoreRecord storeRecord = (TfStoreRecord) objectSyncResultInfo.getData().get(i);

                                            if (max_time < storeRecord.getUPDATETIME()) {
                                                max_time = storeRecord.getUPDATETIME();
                                            }
                                            session.insertOrReplace(storeRecord);
                                        }

                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(max_time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                        Log.d("look", "table_type:" + type + " tname:" + syncTableRecord.getTABLENAME() + "  objectSyncResultInfo.getData().size():" + objectSyncResultInfo.getData().size() + " max_time" + MyUtil.dateConversion(max_time));
                                    }
                                });

                            }
                        });
                break;
            case 1111:
                Log.e("lookup_tableRecord", "1111");
                LocalRetrofit.createService().syncTableRecord(map)
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<SyncResultInfo<SyncTableRecord>>() {
                            @Override
                            public void onCompleted() {
                                isSync = false;
                                Log.i("syncData", "syncData: isInit->" + isInit);
                                if (isInit) {
                                    taskList.clear();
                                    getTaskType();
                                    Log.i(TAG, "syncData: 5");
                                    iterationTableData();
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                isSync = false;
                                syncNum += 1;

                                task_page_no = 0;
                                //task_table_index++;
                            }

                            @Override
                            public void onNext(SyncResultInfo<SyncTableRecord> objectSyncResultInfo) {

                                task_page_no = 0;
                                // task_table_index++;


                                for (int i = 0; i < objectSyncResultInfo.getData().size(); i++) {
                                    SyncTableRecord tableRecord = (SyncTableRecord) objectSyncResultInfo.getData().get(i);
                                    Log.e("lookup_tableRecord", "tableRecord.getTABLENAME():" + tableRecord.getTABLENAME());
                                    long time = 0;


                                    if (time < Long.parseLong(tableRecord.getUPDATETIME())) {
                                        time = Long.parseLong(tableRecord.getUPDATETIME());
                                    }

                                    if (i == objectSyncResultInfo.getData().size() - 1) {
                                        if (syncTableRecord != null) {
                                            syncTableRecord.setUPDATETIME(String.valueOf(time));
                                            syncTableRecord.setISM_STATUS("1");
                                            session.update(syncTableRecord);
                                        }
                                    }
                                    //session.insertOrReplace(tableRecord);
                                    List<SyncTableRecord> recordList = session.queryBuilder(SyncTableRecord.class)
                                            .where(SyncTableRecordDao.Properties.TABLENAME.eq(tableRecord.getTABLENAME())).build().list();
                                    SyncTableRecord record;
                                    if (recordList.isEmpty()) {
                                        record = null;
                                    } else {
                                        record = recordList.get(0);
                                    }
                                    if (record != null) {
                                        // 已存在这条，则更新数据
                                        session.update(tableRecord);
                                        continue;
                                    }
                                    session.insert(tableRecord);
                                }
                                //syncData();
                                Log.i("syncData", "syncData: isInit->");
                            }
                        });
                break;
        }


    }
    private void exit() {
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    private int task_page_no = 0;
    private int task_table_index = 0;

    public void taskTable() {
        mExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    if (MyUtil.networkState) {
                        if (!isSync) {
                            Log.e("look", "task_table_index:" + task_table_index + " task_page_no:" + task_page_no);
                            iterationTableData();
                        }
                    }
                } catch (Exception e) {
                    isSync = false;
                    e.printStackTrace();
                }
            }
        }, 0, MyConstant.HEARTBEAT_INTERVAL_TIME_, TimeUnit.SECONDS);
    }

    /**
     * 迭代循环 所有表的所有页的数据
     */
    private void iterationTableData() {
        Log.i(TAG, "iterationTableData: ");

        if (task_table_index >= taskList.size()) {

            if (isInit) {
                if (isFirstIn) {
                    SharedPreferences preferences = getSharedPreferences("first_pref", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putBoolean("isFirstIn", false);
                    editor.commit();
                }
                Log.e("syncData", "同步数据完成以后");
                //同步数据完成以后
                isInit = false;
                //隐藏 同步中的 弹窗
                gUiHandler.sendEmptyMessage(CANCEL_PROGRESS_DIALOG);
                gUiHandler.sendEmptyMessage(SHOW_BIND_SUCC);
//                //跳转到登录界面
//                gUiHandler.obtainMessage(MyConstant.REPLACE_FRAGMENT_NORMAL, new LoginFragment()).sendToTarget();

                return;
            }

            getTaskType();

            task_table_index = 0;
            verifyMachineDate();

            if (syncNum >= 12) {
                gUiHandler.sendEmptyMessage(CANCEL_PROGRESS_DIALOG);
            }

            try {
                copy();
            } catch (Exception e) {
            }
        }


        TaskBean bean = taskList.get(task_table_index);
        Log.e("TaskBeanbean", "task_table_index:" + task_table_index);
        if (a == 0) {
            a++;
            for (int i = 0; i < taskList.size(); i++) {
                Log.e("TaskBeanbean", "task:" + taskList.get(i).toString());
            }
        }


        if (bean != null) {
            isSync = true;
            SharedPreferences preferences = getSharedPreferences("first_pref", MODE_PRIVATE);
            isFirstIn = preferences.getBoolean("isFirstIn", true);
            if (isFirstIn) {
                Long time = null;
                Date date = null;
                try {
                    String time2 = "1970-01-01 08:00:00";
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    date = format.parse(time2);
                    time = date.getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Log.i("syncData", "1:" + bean.getTableName() + ": 1970-01-01 08:00:00");
                if ("1111".equals(bean.getType())) {
                    syncTable(bean.getType(), bean.getTableName(), bean.getUpdatetime(), task_page_no);
                } else {
                    syncTable(bean.getType(), bean.getTableName(), time, task_page_no);
                }
            } else {
                Log.i("syncData", "2:" + bean.getTableName() + ": " + bean.getUpdatetime());
                syncTable(bean.getType(), bean.getTableName(), bean.getUpdatetime(), task_page_no);
            }

        }
    }

    int a = 0;

    /**
     * 根据sync_table_record 数据定时更新指定表
     */
    public void regularlyUpdateTable() {
        getTaskType();
        taskTable();
    }

    /**
     * 判断本地数据是否和服务器数据数量相等
     */
    public void verifyDataNum(final int type) {
        String updateTime = "1000-01-0100:00:00";
        String clienCode = MyConstant.gSharedPre.getString(MyConstant.CLIENT_CODE, "");
        String storeCode = MyConstant.gSharedPre.getString(MyConstant.STORE_CODE, "");
        final Map<String, Object> map = new HashMap<String, Object>();
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("updatetime", updateTime);
        map.put("client_code", clienCode);
        map.put("store_code", storeCode);
        map.put("api", "1");
        map.put("pageNo", "0");


        Object obj = null;
        String primaryKey = "";
        String tableName = "";
        switch (type) {
            case 0://商品表
                primaryKey = "CI_ID";
                tableName = "commodity_record";
                obj = new CommodityRecord();
                break;
            case 1://商品类型
                primaryKey = "SQENO";
                tableName = "commodity_type_record";
                obj = new CommodityTypeRecord();
                break;
            case 2://会员类型
                primaryKey = "SQENO";
                tableName = "member_type_record";
                obj = new MemberTypeRecord();
                break;
            case 3://店铺配置
                primaryKey = "SQENO";
                tableName = "store_config";
                obj = new StoreConfig();
                break;
            case 4://会员卡信息
                primaryKey = "IC_ID";
                tableName = "tf_cardinfo";
                obj = new TfCardInfo();
                break;
            case 5://折扣表
                primaryKey = "SQENO";
                tableName = "tf_discount_record";
                obj = new TfDiscountRecord();
                break;
            case 6://餐次
                primaryKey = "MT_ID";
                tableName = "tf_mealtimes";
                obj = new TfMealTimes();
                break;
            case 7://账户表
                primaryKey = "ACCOUNT_ID";
                tableName = "tf_member_account_record";
                obj = new TfMemberAccountRecord();
                break;
            case 8://会员表
                primaryKey = "MI_ID";
                tableName = "tf_memberinfo";
                obj = new TfMemberInfo();
                break;
            case 9://打印任务
                primaryKey = "SQENO";
                tableName = "tf_print_task";
                obj = new TfPrintTask();
                break;
            case 10://用户表
                primaryKey = "U_ID";
                tableName = "tf_userinfo";
                obj = new TfUserInfo();
                break;
            case 11://商店表
                primaryKey = "STORE_ID";
                tableName = "tf_store_record";
                obj = new TfUserInfo();
                break;
        }

        if (obj == null || primaryKey.isEmpty() || tableName.isEmpty()) {
            Log.d("look", "return :" + tableName);
            return;
        }
        map.put("tableName", tableName);
        map.put("primaryKey", primaryKey);


        final List<?> dbList = session.queryBuilder(obj.getClass())
                .build()
                .list();
        final SyncTableRecord record = session.queryBuilder(SyncTableRecord.class)
                .where(SyncTableRecordDao.Properties.TABLENAME.eq(tableName))
                .build().unique();

        final String finalTableName = tableName;
        Log.e(TAG, "心跳--check" + tableName);
        LocalRetrofit.createService()
                .getTableTotalNum(map)
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<TotalNum>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
//                        Log.d(TAG, "123 onError: " + e.getMessage());
                    }

                    @Override
                    public void onNext(TotalNum totalNum) {
                        if (totalNum != null && totalNum.getData() >= 0) {
                            Log.d("look", "onNext: tableName : " + finalTableName + "  totalNum " + totalNum.getData() + " 本地数据量：" + dbList.size());
                            if (dbList.size() != totalNum.getData()) {
                                if (record != null) {
                                    record.setUPDATETIME("0");
                                    session.update(record);
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 从数据库中获取所有需要 同步的表格
     */
    public void getTaskType() {
        DaoSession session = MyApplication.getInstance();
        List<SyncTableRecord> tableRecordList = session.queryBuilder(SyncTableRecord.class)
                .build()
                .list();
        taskList.clear();
        if (tableRecordList != null && tableRecordList.size() > 0) {
            if (tableRecordList != null) {
                for (SyncTableRecord tableRecord : tableRecordList) {
                    int type = -1;
                    // region 根据名称判断要更新的表
                    switch (tableRecord.getTABLENAME()) {
                        case "commodity_record":
//                            type = 0;
                            break;
                        case "commodity_type_record":
//                            type = 1;
                            break;
                        case "tf_mealtimes_chipcategory_relation":
                            break;
                        case "member_type_record":
//                            type = 2;
                            break;
                        case "store_config":
                            type = 3;
                            break;
                        case "tf_cardinfo":
//                            type = 4;
                            break;
                        case "tf_discount_record":
//                            type = 5;
                            break;
                        case "tf_mealtimes":
//                            type = 6;
                            break;
                        case "tf_member_account_record":
//                            type = 7;
                            break;
                        case "tf_memberinfo":
//                            type = 8;
                            break;
                        case "tf_print_task":
//                            type = 9;
                            break;
                        case "tf_userinfo":
                            type = 10;
                            break;
                        case "tf_store_record":
//                            type = 11;
                            break;
                        case "commodity_img_record":
                            break;
                        case "tf_chip_category":
                            break;
                        case "tf_store_discount_record":
                            break;
                        case "tf_chipinfo":
                            break;
                        case "tf_member_subsidy_config":
                            break;
                    }
                    //endregion
                    if (type != -1) {
                        TaskBean bean = new TaskBean();
                        bean.setTableName(tableRecord.getTABLENAME());
                        bean.setMs(tableRecord.getQUESTTIME());
                        try {
                            bean.setUpdatetime(Long.parseLong(tableRecord.getUPDATETIME()));
                            Log.e("look", "tableRecord.getTABLENAME():" + tableRecord.getTABLENAME() + " tableRecord.getUPDATETIME()：" + tableRecord.getUPDATETIME() + " bean.getUpdatetime():" + bean.getUpdatetime());
                        } catch (Exception e) {
                        }
                        bean.setType(type);
                        taskList.add(bean);
                    }
                }
            }
        }
    }

    public void inlineUpdate() {
        if (OperationFragment.gOperationHandler != null) {
            OperationFragment.gOperationHandler.obtainMessage(OperationFragment.INLINE_UPDATE_ORDER_INFO).sendToTarget();
        }
    }

    /**
     * 判断是否存在登陆信息这个表
     * 或者该表有没有数据
     *
     * @return
     */
    public boolean isExistsUserInfo() {
        DaoSession session = MyApplication.getInstance();
        List<TfUserInfo> userInfoList = session.queryBuilder(TfUserInfo.class).build().list();
        if (userInfoList == null || userInfoList.isEmpty()) {
            return false;
        }
        return true;
    }

    public void repleaseFragmentToStack(BaseFragment fragment) {
        repleaseFragmentInternal(fragment, true);
    }

    public void repleaseFragment(BaseFragment fragment) {
        repleaseFragmentInternal(fragment, false);
    }

    private void repleaseFragmentInternal(BaseFragment fragment, boolean addTostack) {
        Log.d(TAG, "repleaseFragmentInternal: " + fragment.mainFragmentManager);
//        fragmentManager = fragment.mainFragmentManager;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(containerId, fragment);
        if (addTostack) {
            transaction.addToBackStack(null);
        }
        transaction.commit();
    }

    public void setScanCallback(OnScanResultCallback callback) {
        this.callback = callback;
    }

    public void setBarcodeScannerCallback(OnBarcodeScannerCallback callback) {
        Log.d(TAG, "hansen setBarcodeScannerCallback");
        this.barcodeCallback = callback;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        callback.onresult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (callback != null) {
            callback.onNewIntent(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, mIntentFilter, mTechList);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mNfcAdapter.disableForegroundDispatch(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mService != null) {
            unbindService(mConn);
        }
        isDestory = true;
        mExecutor.shutdown();
        pPrinter = null;
//        unregisterReceiver(networkReceiver);
        mContext = null;
        System.exit(0);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (barcodeCallback != null) {
                barcodeCallback.onKey(event);
            }
        }
        return super.dispatchKeyEvent(event);
    }

    public interface OnScanResultCallback {
        void onresult(int requestCode, int resultCode, Intent data);

        void onNewIntent(Intent intent);
    }

    public interface OnBarcodeScannerCallback {
        void onKey(KeyEvent event);
    }

}

